
import Vue from "vue";
import $ from "jquery";

import {wifi,NetWorkState} from "../hos/wifi.js";
import {airkiss} from "../hos/airkiss.js";
import {Udp,UdpDataFormat} from "../hos/udp.js";
import {TcpClient, TcpDataFormat} from "../hos/tcp";

import {Activity} from "./activity.js";

class AirKiss extends Activity{

    onCreate() {
        super.onCreate();

        $(this.find("log")).append("WiFi信息:" + JSON.stringify(wifi.currentApInfo()) + "<br>");

        new Vue({
            el: this.find("start"),
            methods: {
                click: ()=> {
                    this.start();
                }
            }});

        new Vue({
            el: this.find("stop"),
            methods: {
                click: ()=> {
                    this.stop();
                }
            }});

        new Vue({
            el: this.find("connect"),
            methods: {
                click: ()=> {
                    this.connectDevice();
                }
            }});
    }

    udpRecvObserver(event) {
        this.stop();
        alert("配对成功" + JSON.stringify(event.data));
        // TODO 解析出设备tcp服务地址，发起连接
        this.connectDevice();
    }

    connectDevice() {
        alert("连接设备");
        if (this.tcpClientForDevice) {
            this.tcpClientForDevice.destroy();
        }
        this.tcpClientForDevice = new TcpClient("10.20.50.210", 1234, TcpDataFormat.TEXT);
        this.tcpClientForDevice.addRecvObserver((event)=>{
            const packet = event.data;
            // 测试:收到什么回复什么
            this.tcpClientForDevice.send(packet.data, TcpDataFormat.TEXT).catch(
                (error)=>alert(error.errMsg)
            );
        });

        this.tcpClientForDevice.addDisconnectObserver((event)=>{
            alert("设备意外断开");
        });

        this.tcpClientForDevice.connect().then(()=>{
            alert("连接设备成功");
        }, (error)=>{alert(error.errMsg);});

    }

    start() {

        if (wifi.currentApInfo().state !== NetWorkState.WIFI) {
            alert("手机需要先连接WiFi");
            return;
        }

        // 监听10000端口，设备连接上WiFi后会往该端口广播数据
        this.airKissUdp = new Udp();
        this.airKissUdp.addRecvObserver(this.udpRecvObserver, this);
        this.airKissUdp.bind(10000, UdpDataFormat.TEXT)
            .then(()=>{
                alert("开始配网");
                // TODO 获取用户输入的WiFi密码，开始配网
                airkiss.start("T28T28T28");
                this.airKissTimer = window.setTimeout(()=>{
                    this.stop();
                    alert("配网超时，请检测密码和设备后重试");
                }, 60 * 1000);
            }).catch((error)=>alert(error.errMsg));
    }

    stop() {
        // 关闭定时器
        if(this.airKissTimer) {
            window.clearTimeout(this.airKissTimer);
            this.airKissTimer = null;
        }
        // 关闭socket
        if(this.airKissUdp) {
            this.airKissUdp.destroy();
            this.airKissUdp = null;
        }
        airkiss.stop();
    }

    /**
     * 监听网络状态变化
     * @type NetWorkStateObserver
     * @param {NetWorkStateObserverEvent} event
     */
    stateObserver(event) {
        let state = event.data.state;
        if (state === NetWorkState.WIFI) {
            $(this.find("log")).append("网络状态变化:" + "连接上WiFi" + "<br>");
            $(this.find("log")).append("WiFi信息:" + JSON.stringify(wifi.currentApInfo()) + "<br>");
        } else if (state === NetWorkState.CELLULAR) {
            $(this.find("log")).append("网络状态变化:" + "当前使用流量，请连接WiFi" + "<br>");
        } else if (state === NetWorkState.NONE) {
            $(this.find("log")).append("网络状态变化:" + "未连接网络，请连接WiFi" + "<br>");
        }
    }

    onResume() {
        super.onResume();
        // 监听网络状态变化
        wifi.addNetWorkStateObserver(this.stateObserver, this);
    }

    onPause() {
        super.onPause();
        // 移除网络状态变化监听
        wifi.removeNetWorkStateObserver(this.stateObserver);
        // 确保退出的时候配网处于关闭状态
        this.stop();

        if (this.tcpClientForDevice) {
            this.tcpClientForDevice.destroy();
            this.tcpClientForDevice = null;
        }
    }

}

export {AirKiss};
